import java.util.HashMap;
import java.util.Map;
//https://leetcode.cn/problems/contiguous-array/submissions/559354404/
class Solution {
    public int findMaxLength(int[] nums) {
        //数组和为k -> 数组和为0
        Map<Integer, Integer> map = new HashMap<>();
        int sum = 0;
        map.put(0, -1);
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += (nums[i] == 0 ? -1 : 1);
            if (map.containsKey(sum)) max = Math.max(i - (map.get(sum) + 1) + 1, max);
            else map.put(sum, map.getOrDefault(sum, i));
        }
        return max;
    }
}